package com.battle.pojo.converter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.persistence.AttributeConverter;
import jakarta.persistence.Converter;

/**
 * @author anni.zhu
 * @author anni.zhu@king-v.com
 * Created in 2024/8/28 14:16
 */
@Converter(autoApply = false)
public abstract class ObjectConverter<T>  implements AttributeConverter<T, String> {

    private final ObjectMapper objectMapper = new ObjectMapper ();
    private final TypeReference<T> typeReference = new TypeReference<T> () {

    };

    @Override
    public String convertToDatabaseColumn(T metaDto) {
        try {
            // 将 MetaDto 转换为 JSON 字符串
            return objectMapper.writeValueAsString (metaDto);
        } catch (JsonProcessingException e) {
            // 处理转换异常
            throw new RuntimeException ("Could not convert MetaDto to JSON string", e);
        }
    }

    @Override
    public T convertToEntityAttribute(String dbData) {
        try {
            // 将 JSON 字符串转换为 MetaDto
            return objectMapper.readValue (dbData, typeReference);
        } catch (Exception e) {
            // 处理转换异常
            throw new RuntimeException ("Could not convert JSON string to MetaDto", e);
        }
    }

}
